package com.stark.lock.boot.config;

import com.stark.lock.aspect.DistributedLockAspect;
import com.stark.lock.boot.properties.DistributedLockProperties;
import io.micrometer.common.util.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.locks.LockRegistry;

/**
 * 分布式锁自动配置
 *
 * @author <a href="mailto:mengbin@hotmail.com">Ben</a>
 * @version 1.0.0
 * @since 1.0.0
 */
@Configuration
public class DistributedLockAutoConfig {

    @Configuration
    @ConditionalOnClass(name = "org.springframework.integration.redis.util.RedisLockRegistry")
    @EnableConfigurationProperties(DistributedLockProperties.class)
    protected static class RedisDistributedLockConfig {

        @Bean
        @ConditionalOnMissingBean(LockRegistry.class)
        public LockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory, DistributedLockProperties distributedLockProperties) {
            String registryKey = "distributedLock";
            if (StringUtils.isNotBlank(distributedLockProperties.getRedis().getCacheName())) {
                registryKey = distributedLockProperties.getRedis().getCacheName() + "::" + registryKey;
            }
            return new RedisLockRegistry(redisConnectionFactory, registryKey);
        }

        @Bean
        public DistributedLockAspect distributedLockAspect(LockRegistry lockRegistry, DistributedLockProperties distributedLockProperties) {
            return new DistributedLockAspect(lockRegistry, distributedLockProperties.getRedis().getTimeout());
        }

    }

}
